package logic

import (
	"code-guard/model/mysql"
	"context"
	"errors"

	"code-guard/coderpc/coderpc"
	"code-guard/coderpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *coderpc.UpdateRequest) (*coderpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	mysql.DB.Debug().Where("username = ?", in.Username).Find(&users)
	if users.ID != 0 {
		return nil, errors.New("账号已存在，请更换")
	}

	user := mysql.User{
		Model:    gorm.Model{ID: uint(in.UserId)},
		Username: in.Username,
		Password: in.Password,
		Tel:      in.Tel,
	}

	err := mysql.DB.Debug().Where("id = ?", in.UserId).Updates(&user).Error
	if err != nil {
		return nil, err
	}

	return &coderpc.UpdateResponse{
		Username: user.Username,
		Password: user.Password,
	}, nil
}
